const Sequelize = require('sequelize');

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  'postgres://postgres:password@localhost:6432/postgres';

async function makeNewProject(newprojectReq) {
  console.log('new project start', newprojectReq);
  try {
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
    var res = await sequelize.query(
      'BEGIN;' +
        'INSERT INTO project_member( user_id, project_id, role, state, create_by) values (:userId, :projectId, :role, :state, :createBy); ' +
        'COMMIT;',
      {
        replacements: {
          projectId: newprojectReq.id,
          userId: newprojectReq.owner_id,
          createBy: newprojectReq.create_by,
          role: 'owner',
          state: 'normal'
        }
      }
    );
    if (
      newprojectReq.owner_id !== newprojectReq.create_by &&
      newprojectReq.create_by !== null
    ) {
      var res = await sequelize.query(
        'BEGIN;' +
          'INSERT INTO project_member( user_id, project_id, role, state, create_by) values (:userId, :projectId, :role, :state, :createBy); ' +
          'COMMIT;',
        {
          replacements: {
            projectId: newprojectReq.id,
            userId: newprojectReq.create_by,
            createBy: newprojectReq.create_by,
            role: 'admin',
            state: 'normal'
          }
        }
      );
    }
    console.log('new project ok', newprojectReq);
    return res;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.makeNewProject = makeNewProject;
